<?php

namespace app\controller;

use app\BaseController;


class Paypal extends BaseController
{


    //生成订单
    public function pay()
    {
        $accessToken  =  $this->token();
        // $orderUrl = "https://api-m.paypal.com/v2/checkout/orders";      // 生产环境
        $orderUrl = "https://api-m.sandbox.paypal.com/v2/checkout/orders";  // 沙盒环境

        $orderData = [
            "intent" => "CAPTURE", // 订单意图: CAPTURE 或 AUTHORIZE
            "purchase_units" => [
                [
                    "amount" => [
                        "currency_code" => "USD",  // 货币类型
                        "value" => "1.00"        // 总金额
                    ]
                ]
            ],
        "application_context" => [
                        "return_url" => "https://h5pay.mujuapi.cn/#/pages/zfcg/zfcg", // 付款成功后的回调URL
                        "cancel_url" => "https://h5pay.mujuapi.cn/#/pages/zfqx/zfqx"  // 付款取消后的回调URL
                    ]
        ];

        // 将数组转换为JSON字符串
        $jsonData = json_encode($orderData);
        // 设置HTTP上下文用于POST请求
        $options = array(
            'http' => array(
                'method'  => 'POST',
                'header'  => array(
                    'Content-Type: application/json',
                    'Authorization: Bearer ' . $accessToken
                ),
                'content' => $jsonData,
            ),
        );

        // 创建上下文资源
        $context = stream_context_create($options);
        // 使用file_get_contents发送POST请求
        $response = file_get_contents($orderUrl, false, $context);
        return json(json_decode($response, true));
    }









    //捕获订单
    public function capture()
    {
        $id = input("id");

        $url = "https://api-m.sandbox.paypal.com/v2/checkout/orders/$id/capture";  // 沙盒环境

        $accessToken  =  $this->token();
        // 设置HTTP上下文用于POST请求
        $options = array(
            'http' => array(
                'method'  => 'POST',
                'header'  => array(
                    'Content-Type: application/json',
                    'Authorization: Bearer ' . $accessToken
                ),
            ),
        );

        // 创建上下文资源
        $context = stream_context_create($options);
        // 使用file_get_contents发送POST请求
        $response = file_get_contents($url, false, $context);
        return json(json_decode($response, true));
    }










    //获取access_token
    public function token()
    {

        // PayPal应用的客户端ID和客户端密钥
        $clientId = 'ASkewmBhq9r7xoLBEecE5Vc2_ZYhM2ve_mVm4a3_-y2ZG34BzmLG1wMIwPChD5UO3VDFcGiNsxFrzQN6';
        $clientSecret = 'EKvevYcu09uV6SIbeuYdu1fuD3668Ih94P6EWaLn3BdSX_jMINTA6uGXE7XvMcgc2iZiVCU_nSL-o9nw';
        // PayPal API URL

        //$url = "https://api-m.paypal.com/v1/oauth2/token"; // 生产环境
        $url = "https://api-m.sandbox.paypal.com/v1/oauth2/token"; // 沙盒环境

        // 使用cURL初始化请求
        $ch = curl_init();
        // 设置cURL的选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 将响应作为字符串返回
        curl_setopt($ch, CURLOPT_POST, 1); // POST请求
        curl_setopt($ch, CURLOPT_USERPWD, $clientId . ":" . $clientSecret); // 基本授权，客户端ID和密钥
        curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials"); // POST数据
        // 设置HTTP头
        $headers = array();
        $headers[] = "Accept: application/json";
        $headers[] = "Accept-Language: en_US";
        $headers[] = "Content-Type: application/x-www-form-urlencoded";
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        // 发送请求并获取响应
        $response = curl_exec($ch);

        // 错误处理
        if (curl_errno($ch)) {
            echo 'cURL error: ' . curl_error($ch);
            curl_close($ch);
            exit();
        }

        // 关闭cURL会话
        curl_close($ch);

        // 将响应字符串转换为PHP数组
        $responseArray = json_decode($response, true);

        // 检查响应中是否包含访问令牌
        // if (isset($responseArray['access_token'])) {
        //     echo "Access Token: " . $responseArray['access_token'];
        // } else {
        //     echo "Error: Unable to get access token";
        // }
        $accessToken = $responseArray['access_token'];

        return $accessToken;
    }
}
